import { PureComponent } from 'react';
import {
  Scene, OrthographicCamera, TextureLoader, BoxGeometry,
  MeshLambertMaterial, Mesh, WebGLRenderer, PointLight,
  SphereGeometry
} from 'three';

class Index extends PureComponent {

  async componentDidMount() {
    const scene = new Scene();

    const renderer = new WebGLRenderer({
      canvas: document.getElementById('mainCanvas')
    });
    
    const camera = new OrthographicCamera(-10, 10, 7.5, -7.5, 0.1, 100);
    camera.position.set(25, 25, 25);
    camera.lookAt(0, 0, 0);

    const geometry = new BoxGeometry(5, 5, 5);
    // const geometry = new SphereGeometry(5, 25, 15);

    const light = new PointLight(0xffffff, 1, 1000);
    light.position.set(10, 15, 20);
    scene.add(light);

    //教程中的代码使用的是ImageUtils.loadTexture, 但在新版本中已被废弃
    //所以这里采用了新的写法
    const textureLoader = new TextureLoader();
    //法一: 先加载材质, 然后创建网格再渲染
    // const texture = await textureLoader.loadAsync('/img/0.png');
    // const material = new MeshLambertMaterial({
    //   map: texture
    // });

    // const mesh = new Mesh(geometry, material);
    // scene.add(mesh);

    // renderer.render(scene, camera);
    //法二: 先渲染, 然后再加载材质重绘
    //这是在例5.2.1看到设置材质之后才回过头来添加的方法
    //当然了, 这两种方法都不妥, 第一种会黑一下然后再渲染
    //第二种会先渲染一个'裸体'的几何体, 然后再闪一下被添加纹理
    //最优解是给一个loading, 然后去加载材质, 加载完毕之后再渲染页面
    let texture = null;
    const material = new MeshLambertMaterial({
      map: texture
    });

    const mesh = new Mesh(geometry, material);
    textureLoader.loadAsync('/img/0.png').then(
      texture => {
        mesh.material = new MeshLambertMaterial({
          map: texture
        });
        renderer.render(scene, camera);
      }
    );
    scene.add(mesh);

    renderer.render(scene, camera);
    
  }

  render() {

    return (
      <canvas
        id="mainCanvas"
        width="400"
        height="300"
      />
    );
  }

}

export default Index;